package com.xgame.server.netty;

import com.xgame.server.netty.enity.MsgEntity;
import com.xgame.server.netty.service.MessageService;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class QueueInstance extends Thread {

    private static QueueInstance queueInstance = null;
    private final BlockingQueue<MsgEntity> queue = new LinkedBlockingQueue<MsgEntity>();

    public MessageService getMessageService() {
        return messageService;
    }

    public QueueInstance setMessageService(MessageService messageService) {
        if(this.messageService == null){
            this.messageService = messageService;
        }
        return this;
    }


    private MessageService messageService;
    public static synchronized QueueInstance getInstance() {
        if (queueInstance == null) {
            queueInstance = new QueueInstance();
        }
        return queueInstance;
    }

    private QueueInstance() {
        super("CLogOracleWriterThread");
    }

    public void offerQueue(MsgEntity t) {
        try {
            queue.offer(t);
        } catch (Exception e) {

        }
    }
    @Override
    public void run() {

        List<MsgEntity> bufferedLogList = new ArrayList<MsgEntity>(); // 缓冲队列
        while (true) {
            try {
                bufferedLogList.add(queue.take());
                queue.drainTo(bufferedLogList);
                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    // 写入日志
                    for(MsgEntity log:bufferedLogList){
                        messageService.handleMsg(log);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 防止缓冲队列填充数据出现异常时不断刷屏
                try {
                    Thread.sleep(1000);
                } catch (Exception eee) {
                }
            } finally {
                if (bufferedLogList != null && bufferedLogList.size() > 0) {
                    try {
                        bufferedLogList.clear();
                    } catch (Exception e) {
                    }
                }
            }
        }

    }
}
